package com.zeng.configuration.microprofile.config.converter;

import org.eclipse.microprofile.config.spi.Converter;

import java.util.HashSet;
import java.util.Set;

/**
 * @author zyb
 * @date 2021-03-14 13:49
 */
public class StringToBooleanConverter implements Converter<Boolean> {

    private static final Set<String> trueValues = new HashSet<>(4);

    private static final Set<String> falseValues = new HashSet<>(4);

    static {
        trueValues.add("true");
        trueValues.add("on");
        trueValues.add("yes");
        trueValues.add("1");

        falseValues.add("false");
        falseValues.add("off");
        falseValues.add("no");
        falseValues.add("0");
    }
    /**
     * Convert the given string value to a specified type. Callers <em>must not</em> pass in {@code null} for
     * {@code value}; doing so may result in a {@code NullPointerException} being thrown.
     *
     * @param value the string representation of a property value (must not be {@code null})
     * @return the converted value, or {@code null} if the value is empty
     * @throws IllegalArgumentException if the value cannot be converted to the specified type
     * @throws NullPointerException     if the given value was {@code null}
     */
    @Override
    public Boolean convert(String value) throws IllegalArgumentException, NullPointerException {
        value = value.trim();
        if ("".equals(value)) {
            return null;
        }
        value = value.toLowerCase();
        if (trueValues.contains(value)) {
            return Boolean.TRUE;
        }
        else if (falseValues.contains(value)) {
            return Boolean.FALSE;
        }
        else {
            throw new IllegalArgumentException("Invalid boolean value '" + value + "'");
        }
    }
}
